import { filterAuth } from '@/support/common';
import { transferOption } from '@/support/utils';
import { PlusOutlined } from '@ant-design/icons';
import { Badge, Button, Card, message, Tag } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import AddModal from './addModal';
import EditModal from './editModal';
import ResetPwdModal from './resetPwdModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  account: state.account,
  loading: state.loading.effects['account/postFetchPage'],
  user: state?.menu?.userProfile,
});
let pageObj = {};
class Account extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      roleOption: [],
      roleData: [],
      orgOption: [],
      addVisible: false,
      editVisible: false,
      resetRecord: {},
      resetVisible: false,
      currentAccount: {},
      currentActionType: 'add',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/postFetchPage',
      payload: { url: '/account/findbypage' },
    });
    this.getRoleOption();
    this.getOrgOption();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/initData',
    });
  }

  getRoleOption = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/getData',
      payload: {
        url: '/account/findrole',
      },
      callback: (response: any) => {
        this.setState({
          roleData: response.data,
          roleOption: response.data ? transferOption(response.data, ['roleCode', 'roleName']) : [],
        });
      },
    });
  };

  getOrgOption = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/getData',
      payload: {
        url: '/account/findorgtree',
      },
      callback: (response: any) => {
        if (response.data) {
          this.setState({
            orgOption: this.fotmatOrgTree(response.data),
          });
        }
      },
    });
  };

  fotmatOrgTree = data => {
    return data.map(d => {
      if (d.children) {
        this.fotmatOrgTree(d.children);
      }
      d.title = d.orgName;
      d.value = d.sid;
      return d;
    });
  };

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'account/postFetchPage',
      payload: { url: '/account/findbypage', ...formValues },
    });
  };

  handleAdd = () => {
    this.setState({
      addVisible: true,
      currentActionType: 'add',
    });
  };

  closeAddModal = () => {
    this.setState({
      addVisible: false,
      currentActionType: 'add',
      currentAccount: {},
    });
  };

  handleCopy = record => {
    this.setState({
      addVisible: true,
      currentActionType: 'copy',
      currentAccount: record,
    });
  };

  handleEdit = record => {
    this.setState({
      editVisible: true,
    });
    this.editForm.setData(record);
  };

  closeEditModal = () => {
    this.setState({
      editVisible: false,
    });
  };

  handleResetPwd = record => {
    this.setState({
      resetRecord: record,
      resetVisible: true,
    });
  };

  handleRefresh = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    let params = { ...formValues, page: pageObj.current, size: pageObj.pageSize };
    dispatch({
      type: 'account/postFetchPage',
      payload: { url: '/account/findbypage', ...params },
    });
  };

  handleNotice = () => {
    message.success('操作成功');
    this.handleRefresh();
  };

  handleNoticeDel = () => {
    message.success('删除成功');
    const { dispatch } = this.props;
    const { formValues } = this.state;
    let params = { ...formValues, page: pageObj.current, size: pageObj.pageSize };
    dispatch({
      type: 'account/postFetchPage',
      payload: { url: '/account/findbypage', ...params },
      callback: (response: any) => {
        if (!response.data.records || response.data.records.length === 0) {
          let obj = {
            ...formValues,
            page: pageObj.current - 1 < 1 ? 1 : pageObj.current - 1,
            size: pageObj.pageSize,
          };
          dispatch({
            type: 'account/postFetchPage',
            payload: { url: '/account/findbypage', ...obj },
          });
        }
      },
    });
  };

  handleLock = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/postDataWithRes',
      payload: { url: '/account/lock', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.handleNotice();
        }
      },
    });
  };

  handleUnlock = sid => {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/postDataWithRes',
      payload: { url: '/account/unlock', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.handleNotice();
        }
      },
    });
  };

  handleDelete = sid => {
    const { dispatch } = this.props;
    dispatch({
      type: 'account/postDataWithRes',
      payload: { url: '/account/delete', sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.handleNoticeDel();
        }
      },
    });
  };

  render() {
    const {
      account: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
      user,
    } = this.props;
    pageObj = pagination;
    const {
      formValues,
      addVisible,
      roleOption,
      roleData,
      orgOption,
      editVisible,
      resetRecord,
      resetVisible,
      currentActionType,
      currentAccount,
    } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '登录账号',
        dataIndex: 'accountName',
        render: (text: any) => {
          return <MaskText text={text} type="name" />;
        },
      },
      /* {
        title: '昵称',
        dataIndex: 'nickName',
      }, */
      /* {
        title: '手机号码',
        dataIndex: 'userMobile',
      }, */
      {
        title: '所属租户',
        dataIndex: 'tenantName',
      },
      {
        title: '所属角色',
        dataIndex: 'roleName',
        render: (text: any, record: any) => {
          if (text) {
            return text.split(',').map((item: any, index: any) => (
              <Tag color="purple" key={record.accountName + 'role' + index}>
                {item}
              </Tag>
            ));
          } else {
            return text;
          }
        },
      },
      {
        title: '所属组织',
        dataIndex: 'orgName',
        render: (text: any, record: any) => {
          if (text) {
            return text.split(',').map((item: any, index: any) => (
              <Tag color="green" key={record.accountName + 'org' + index}>
                {item}
              </Tag>
            ));
          } else {
            return text;
          }
        },
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        render: (text: any) => {
          return <MaskText text={text} type="phone" />;
        },
      },
      {
        title: '邮箱',
        dataIndex: 'mail',
        render: (text: any) => {
          return <MaskText text={text} type="email" />;
        },
      },
      {
        title: '账号类型',
        dataIndex: 'accountType',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '普通账号';
            case '1':
              return '租户管理员';
            case '2':
              return '超管';
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '账号状态',
        dataIndex: 'accountStatus',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return <Badge status="success" text="正常" />;
            case '1':
              return <Badge status="warning" text="锁定" />;
            case '2':
              return <Badge status="error" text="失效" />;
            default:
              break;
          }
          return text;
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render: (text: any) => {
          return <MaskText text={text} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 230,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'account_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '复制账号',
              key: 'copy',
              auth: 'account_doCopy',
              onConfirm: () => this.handleCopy(record),
            },
            /* {
              title: '数据权限',
              key: 'permission',
              auth: 'account_doPermission',
              onConfirm: () => this.handlePermission(record),
            }, */
            {
              title: '删除',
              key: 'del',
              auth: 'account_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.sid),
            },
            {
              title: '重置密码',
              key: 'resetPwd',
              auth: 'account_doResetPwd',
              onConfirm: () => this.handleResetPwd(record),
            },
          ];
          if (record.accountStatus === 0) {
            btns.push({
              title: '锁定',
              key: 'lock',
              auth: 'account_doLock',
              message: '是否确认锁定？',
              Popconfirm: true,
              onConfirm: () => this.handleLock(record.sid),
            });
          } else if (record.accountStatus === 1) {
            btns.push({
              title: '解锁',
              key: 'unlock',
              auth: 'account_doUnlock',
              message: '是否确认解锁？',
              Popconfirm: true,
              onConfirm: () => this.handleUnlock(record.sid),
            });
          }

          if (
            record.accountType === 1 ||
            !!record.isMerchant || // 商户管理中创建的商户账号，在系统管理-账号管理中无法操作
            record.accountName === user?.accountName // 自己的账号本人不能操作，隐藏操作区按钮
          ) {
            btns.splice(0, btns.length);
          }

          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '登录账号',
        key: 'accountName',
      },
      /* {
        type: 'input',
        title: '昵称',
        key: 'nickName',
      }, */
      {
        type: 'input',
        title: '所属组织',
        key: 'orgName',
      },
      {
        type: 'select',
        title: '所属角色',
        key: 'roleCode',
        selectOptions: roleData,
        keyValue: ['roleCode', 'roleName'],
      },
      {
        type: 'select',
        title: '账号状态',
        key: 'accountStatus',
        selectOptions: [
          { label: '正常', value: 0 },
          { label: '锁定', value: 1 },
          { label: '失效', value: 2 },
        ],
      },
      /* {
        type: 'input',
        title: '手机号码',
        key: 'userMobile',
      }, */
      {
        type: 'select',
        title: '账号类型',
        key: 'accountType',
        selectOptions: [
          { label: '普通账号', value: 0 },
          { label: '租户管理员', value: 1 },
        ],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'account/postFetchPage', url: '/account/findbypage' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('account_doAdd', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'account/postFetchPage', url: '/account/findbypage' }}
            formValues={formValues}
          />
        </Card>
        <AddModal
          modalVisible={addVisible}
          roleOption={roleOption}
          orgOption={orgOption}
          type={currentActionType}
          data={currentAccount}
          closeModal={this.closeAddModal}
        />
        <EditModal
          onRef={(val: any) => (this.editForm = val)}
          modalVisible={editVisible}
          roleOption={roleOption}
          orgOption={orgOption}
          closeModal={this.closeEditModal}
          pageObj={pageObj}
          formValues={formValues}
        />
        <ResetPwdModal
          modalVisible={resetVisible}
          record={resetRecord}
          closeModal={() => this.setState({ resetVisible: false })}
          pageObj={pageObj}
          formValues={formValues}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(Account);
